package lgrpccurator.demo.controller;

import lgrpccurator.demo.zookeeperRegister.ZookeeperRegister;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ApplicationRunnerImpl  implements ApplicationRunner {

    @Autowired
    ZookeeperRegister regster;

    @Autowired
    private ZooKeeper zkClient;

    public String GetData() throws Exception {

        // 创建一个watcher
        List<String> children = zkClient.getChildren("/server", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath() + "数据发生了变化！====>" + event.getType()+
                        event.getPath()+"----"+event.getState()+event.getState());
                try {
                    String newResult = GetData();
                    System.out.println("新的结果是：" + newResult);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, null);

        for(String c: children){
            String path = "/server/"+c;
            zkClient.getData(path,new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                 System.out.println(event.getPath() + "数据发生了变化！====>" + event.getType()+
                         event.getPath()+"----"+event.getState()+event.getState());
                try {
                    String newResult = GetData();
                    System.out.println("新的结果是：" + newResult);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            },null);
        }





        // 创建一个watcher
   /*     byte[] data = zkClient.g("/server", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath() + "数据发生了变化！====>" + event.getType() +
                        event.getPath() + "----" + event.getState() + event.getState());
                try {
                    String newResult = GetData();
                    System.out.println("新的结果是：" + newResult);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, null);*/


        return null;

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("通过实现ApplicationRunner接口，在spring boot项目启动后打印参数");
        String s = GetData();


    }
}